var app = getApp();
var constract = require('../../utils/constract.js');
var proof = require('../../utils/proof.js');

var oldCompany, newCompany, dirty = false;

// function showOther(token, type, callback, id) {
//   wx.request({
//     url: constract.other, //他人详情
//     header: { token: token },
//     data: { passiveUid: 0, type: type, cardId: id },
//     success: callback,
//     fail: (err) => {
//       console.log(err);
//     }
//   })
// }

/**
 * 表单已经提交成功页面跳转
 * @param {Object} that 对this的保留
 * @param {string} url  保存成功页面跳转路径
 */
function hasSave(that, url){
  //上传 + 编辑成功跳转
  app.globalData.company = [];
  
  wx.showToast({
    title: '保存成功',
    icon: 'success',
    mask: true,
    duration: 1000
  })

  setTimeout(function () {
    that.setData({
      saved: false
    })
    wx.redirectTo({
      url: url,
    });
  }, 1000)
}

/**
 * 保存方法提取
 * @param {*} that 
 * @param {*} data 
 * @param {*} imgList 
 * @param {*} arr 
 * @param {*} preKey 
 * @param {*} headshot 
 * @param {*} mInput 
 * @param {*} editId 
 */
function saveAll(that,data,imgList,arr,preKey,headshot,mInput,editId){
  // 手动输入验证
  if (mInput) {
    var name = data.name;
    var company = data.company[0];
    var title = data.title[0];
    var telCell = data.telCell;
    var email = data.email;
    for (var i = 0; i < email.length; i++) {
      if (proof.trim(email[i]) !== '') {
        if (!proof.isEmail(email[i])) {
          wx.showModal({
            title: '提示',
            content: '请输入正确的邮箱格式',
            showCancel: false
          });
          return;
        }
      };
    }
    for (var i = 0; i < telCell.length; i++) {
      if (!proof.isMobile(telCell[i])) {
        wx.showModal({
          title: '提示',
          content: '请输入正确的手机号',
          showCancel: false
        });
        return;
      };
    }
    if (proof.trim(name) == '') {
      wx.showModal({
        title: '提示',
        content: '姓名不能为空',
        showCancel: false
      });
      return;
    };
    if (proof.trim(company) == '') {
      wx.showModal({
        title: '提示',
        content: '公司不能为空',
        showCancel: false
      });
      return;
    };
    if (proof.trim(title) == '') {
      wx.showModal({
        title: '提示',
        content: '职位不能为空',
        showCancel: false
      });
      return;
    };


  }

  /*** 验证通用 start ****/
  var company = data.company[0];
  if (!company) {
    wx.showModal({
      title: '提示',
      content: '请输入公司',
      showCancel: false
    });
    return;
  }
  var name = data.name;
  if (!name) {
    wx.showModal({
      title: '提示',
      content: '请输入姓名',
      showCancel: false
    });
    return;
  }

  var wechat = data.wechat;
  if (that.data.uploadType == 2 && (!wechat || wechat == "")) {
    wx.showModal({
      title: '提示',
      content: '请添加微信号',
      showCancel: false
    })
    return;
  }

  // var source = data.source;
  // if(!source){ //来源必填
  //   wx.showModal({
  //     title: '提示',
  //     content: '请选择来源',
  //     showCancel: false
  //   });
  //   return;
  // }

  /******* 验证通用 end *********/

  if (wx.showLoading) {
    wx.showLoading({
      title: '保存中',
      mask: true,
    });
  }
  that.setData({
    saved: true
  })

  app.Verification(function (token) {
    wx.request({
      url: constract.index, //查看首页的名片信息
      header: { token: token },
      success: function (res) {
        var userInfo = res.data.data;
        if (userInfo.state == 0) {
          wx.showModal({
            title: '您还没有名片',
            content: '创建自己的名片，让大家认识你',
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/add-card/add-card?avatar=' + userInfo.avatar + '&name=' + userInfo.name,
                })
              }
            }
          })
        };

        wx.request({
          url: constract.cardAddOrEdit,
          method: "POST",
          header: {
            'content-type': 'application/x-www-form-urlencoded', // 默认值
            token: token
          },
          data: data,
          success: function (res) { //表单上传成功
            if (wx.hideLoading) {
              wx.hideLoading();
            }

            var cardId = res.data.data; //得到cardId

            //上传头像
            if (headshot.img && (res.data.code == 12000) && headshot.flag) {
              if (imgList[0]) { //扫描上传头像
                wx.uploadFile({
                  url: constract.addImg,
                  name: 'avatar',
                  formData: {
                    'id': res.data.data,
                    'cardImg': imgList[0],
                  },
                  filePath: headshot.img,
                  success: function (res) {
                    console.log(res);
                  },
                  fail: function (err) {
                    console.log(err);
                  }
                })
              } else { //手动输入上传头像
                wx.uploadFile({
                  url: constract.addImg,
                  name: 'avatar',
                  formData: {
                    'id': res.data.data,
                  },
                  filePath: headshot.img,
                  success: function (res) {
                    console.log(res);
                  },
                  fail: function (err) {
                    console.log(err);
                  }
                })
              }
            }

            //上传图片背景图
            var tempFilePaths = that.data.tempFilePaths; //上传背面临时路径              
            if (tempFilePaths && (res.data.code == 12000)) {
              if (wx.hideLoading) {
                wx.hideLoading();
              };
              wx.uploadFile({
                url: constract.addImg,
                name: 'backImg',
                formData: {
                  'id': res.data.data,
                  'cardImg': imgList[0],
                },
                filePath: tempFilePaths,
                success: function (res) {

                  if (editId) { 
                    //上传 + 编辑成功跳转 **********************
                    var url = '../details/details?id=' + editId + '&type=0' + '&id=' + cardId + '&ouid=0'
                    hasSave(that, url);

                  } else {
                    //上传 + 新增成功跳转 **********************
                    var url = '../input-card/saved/saved?id=' + cardId + '&name=' + that.data.name;
                    hasSave(that, url);

                  }

                },
                fail: function (err) {
                  that.setData({
                    saved: false
                  })
                  console.log(err);
                }
              })
            } else if (res.data.code == 12000) { // 没有添加背景图的保存
              if (wx.hideLoading) {
                wx.hideLoading();
              };
              // 手动 添加成功跳转 **********************
              if (mInput) {

                var url = '../input-card/saved/saved?id=' + cardId + '&name=' + data.name + '&type=0';
                hasSave(that, url);

              } else if (editId) {
                //编辑成功跳转 *********************
                var url = '../details/details?id=' + editId + '&type=0' + '&ouid=0';
                hasSave(that, url);

              } else {
                //扫描成功跳转 ***********************
                var url = '../input-card/saved/saved?id=' + cardId + '&name=' + that.data.name + '&type=0'
                hasSave(that, url);
                
              }
            } else {
              if (wx.hideLoading) {
                wx.hideLoading();
              };
              that.setData({
                saved: false
              })
              wx.showModal({
                title: '提示',
                content: res.data.msg,
                showCancel: false
              });
              data = {};
              return;
            }

          },
          fail: function (err) {
            that.setData({
              saved: false
            })
            wx.showModal({
              title: '提示',
              content: '保存失败',
              showCancel: false
            });
            console.log(err);
          }
        });
      },
      fail: function (err) {
        console.log(err);
        that.setData({
          saved: false
        })
        wx.showModal({
          title: '提示',
          content: '保存失败',
          showCancel: false
        });
      }
    });
  })
}

/***************************/
Page({
  data: {

    list: [
      { name: 'wechat', title: '微信', img: "/images/wechat.png",show:true},
      { name: 'qq', title: 'QQ', img: "/images/QQ.png",show:true},
      { name: 'company', title: '公司', img: "/images/edit-company.png",show:true},
      { name: 'title', title: '职位', img: "/images/post.png",show:true},
      { name: 'telCell', title: '手机', img: "/images/phone2.png",show:true},
      { name: 'fax', title: '传真', img: "/images/chuanzhen.png",show:true},
      { name: 'email', title: '邮箱', img: "/images/email.png",show:true},
      { name: 'webPage', title: '网页', img: "/images/wangzhi.png",show:true},
      { name: 'addr', title: '地址', img: "/images/dizhi.png",show:true},
      { name: 'commemorateDay', title: '纪念日', img: "/images/jinianri.png",show:true},
      { name: 'birthday', title: '生日', img: "/images/shengri.png",show:true},
      { name: 'maimai', title: '脉脉', img: "/images/maimai.png",show:true}
    ],

    source:'',
    showSource: false,

    headshot: { flag: false, img: '/images/logo.png' },
    listInput: [],
    show: false,
    imgList: [],
    showId: null,
    interval: 3000,
    duration: 500,
    check: true,
    saved: false,
    companySort: [],
    objDate: {},
    itemLength: {
      wechat:0, 
      qq:0,
      company:0, 
      title:0,
      telcell:0,
      fax:0,
      email:0, 
      webpage:0, 
      addr:0, 
      commemorateday:0, 
      birthday:0, 
      maimai:0,
    },
  },
  sumItemLength: function(isAdd,itemKey){
    let that = this;
    let itemLength = that.data.itemLength;

    let mImput = this.data.options.mInput
    if(mImput && mImput === '1') {
      itemLength.company = 1;
      itemLength.title = 1;
      itemLength.telcell = 1;
      itemLength.addr = 1;
      itemLength.email = 1;
      itemLength.webpage = 1;
      itemLength.fax = 1;
    }

    //计算加载的各length [this.data.options.msg]
    if(!wx.getStorageSync('itemLength') && this.data.options.msg){
      let msg = this.data.options.msg;
      if(msg.data){
        msg = msg.data;
      }
      for (var key in msg) {
        let nKey = key.toLowerCase().replace('_','');
        if (Array.isArray(msg[key])) {
          itemLength[nKey] = msg[key].length;  
        }
      }

    } else if(wx.getStorageSync('itemLength')) {
      itemLength = wx.getStorageSync('itemLength');
    }


    if(itemKey) {
      itemLength[itemKey] = isAdd ? itemLength[itemKey]+1 : itemLength[itemKey]-1;
    }

    wx.setStorageSync('itemLength',itemLength);

    let list = this.data.list; 
    for(var key in itemLength) {
        list.forEach(function(item){

          if(itemLength[key] == 10) {
            (item.name.toLowerCase().replace('_','') == key) && (item.show = false); 
            that.setData({
              list: list
            })
          } else if(item.show == false) {
            (item.name.toLowerCase().replace('_','') == key) && (item.show = true); 
            that.setData({
              list: list
            })
          }
          
          
        })
    }

    console.log(itemLength);
  },
  onLoad: function (options) {
    var that = this;

    console.log(options);
    wx.removeStorageSync('itemLength');

    /* 点击编辑进入带入的id */
    var uploadType = options.uploadType;

    var editId = options.editId || '';
    var mInput =  options.mInput || ''; //手动输入or自动输入
    var currentDate = new Date(); //获取当前时间
    
    currentDate = currentDate.getFullYear() + '-' + currentDate.getMonth() + '-' + currentDate.getDate();
    
    that.setData({
      mInput: mInput,
      currentDate: currentDate,
      sourceList: app.globalData.sourceList, 
      uploadType: uploadType,
      options: options
    })

    if (mInput) {
      //手动输入逻辑处理
    } else {
      if (editId) { //编辑
        var msg = options.msg;
        console.log(msg);

        msg = JSON.parse(msg);
        console.log(msg);
        
        for (var key in msg) {
          if (Array.isArray(msg[key])) {
            // console.log(msg[key]);
            for (var i = 0; i < msg[key].length; i++) {
              // msg[key][i] = msg[key][i].replace(/^[^0-9a-zA-Z\u4e00-\u9fa5]/g,'');
              msg[key][i] = msg[key][i].replace(/^[:|：]/g, '');
            }
          }
        }
        
        var avatar = msg.avatar;
        if (avatar) {
          var avaFlag = that.data.headshot;
          avaFlag.flag = true;
          avaFlag.img = avatar;
          that.setData({
            headshot: avaFlag
          })
        }
        that.setData({
          msg: msg
        })
      } else {
        /* 识别后的数据处理 */
        var msg;
        console.log(options.msg);

        var objData = JSON.parse(options.msg);
        console.log(objData);
        
        msg = objData.data;
      }

      msg.companySort = msg.company;
      that.setData(msg);
      console.log(that.data);

      var imgList = this.data.imgList;
      imgList.push(msg.cardImg);
      if (msg.backImg) {
        imgList.push(msg.backImg);
      }
      this.setData({
        imgList: imgList,
        editId: editId,
        cardImg: msg.cardImg
      })
    }

    this.sumItemLength();
  },

  onShow: function () {
    var that = this;
    dirty = false;
    var globalCompany = app.globalData.company;
    if (globalCompany.length > 0) {
      that.setData({
        companySort: globalCompany
      })
    }
  },

  previewImg: function (e) {
    let msg = JSON.parse(this.data.options.msg);
    // console.log(msg);
    // console.log(e);

    var urls = [];
    var src = e.currentTarget.dataset.src;

    var cardImg = msg.cardImg || JSON.parse(msg.data).cardImg;
    var backImg = msg.backImg || this.data.tempFilePaths;
    // var avatar = msg.avatar;
    
    // console.log(cardImg);
    // console.log(backImg);

    // var uploadType = this.data.userInfo.upload;

    cardImg && urls.push(cardImg);
    backImg && urls.push(backImg);

    wx.previewImage({
      current: src,
      urls: urls,
    })
  },

  touchstart: function (e) {
    var id = e.currentTarget.id;

    if (e.touches.length == 1) {

      this.setData({
        startX: e.touches[0].clientX,
        id: id
      })
    }

  },
  touchmove: function (e) {
    var that = this;
    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = that.data.startX - moveX;

      var txtStyle = '';
      if (disX == 0 || disX < 0) {
        txtStyle = "left:0px";
      } else if (disX > 0 && disX < 30) {
        txtStyle = "left:-" + disX + "px";
      } else {
        txtStyle = "left:-110rpx";
      }

      that.setData({
        txtStyle: txtStyle
      })
    };
  },
  touchend: function (e) {

    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;

      var txtStyle = disX > 30 ? "left:-110rpx" : "left:0px";
      this.setData({
        txtStyle: txtStyle
      })
    }
  },
  touchstartidx: function (e) {
    var index = e.target.dataset.index;
    var listInput = this.data.listInput;
    if (e.touches.length == 1) {
      for (var i = 0; i < listInput.length; i++) {
        if (i != index) {
          listInput[i].txtStyle = "left:0px";
        }
      };
      this.setData({
        startX: e.touches[0].clientX,
        listInput: listInput
      })
    }
  },
  touchmoveidx: function (e) {
    var that = this;
    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = that.data.startX - moveX;

      var txtStyle = '';
      if (disX == 0 || disX < 0) {
        txtStyle = "left:0px";
      } else if (disX > 0 && disX < 30) {
        txtStyle = "left:-" + disX + "px";
      } else {
        txtStyle = "left:-110rpx";
      }
      var index = e.currentTarget.dataset.index;
      var listInput = this.data.listInput;
      listInput[index].txtStyle = txtStyle;
      that.setData({
        listInput: listInput
      })
    };
  },
  touchendidx: function (e) {
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var txtStyle = disX > 60 ? "left:-110rpx" : "left:0px";
      var index = e.currentTarget.dataset.index;
      var listInput = this.data.listInput;
      listInput[index].txtStyle = txtStyle;
      this.setData({
        listInput: listInput
      })
    }
  },

  delete: function (e) {
    var that = this;
    var idx = e.currentTarget.dataset.index;
    var attr = e.currentTarget.dataset.title; // 获取的属性名
    var company = e.currentTarget.dataset.company;// 获取删除的公司
    var val = this.data[attr]; // 通过属性名获取属性值

    var itemKey = attr.toLowerCase().replace('_','');
    this.sumItemLength(false,itemKey);

    if (company) {
      var companySort = that.data.companySort;
      var companyIdx = companySort.indexOf(company);
      companySort.splice(companyIdx, 1);
      that.setData({
        companySort: companySort
      })
    }

    if (!isNaN(idx)) {
      val.splice(idx, 1); //改变后的属性值


      var obj = {};
      obj[attr] = val;
      that.setData(obj);

    }

    that.setData({
      txtStyle: "0rpx"
    })

  },
  deleteidx: function (e) {
    var company = e.currentTarget.dataset.company;
    var index = e.currentTarget.dataset.index;
    var listInput = this.data.listInput;
    
    var attr = e.currentTarget.dataset.name;
    var itemKey = attr.toLowerCase().replace('_','');
    this.sumItemLength(false,itemKey);

    if (company) {
      var companySort = this.data.companySort;
      var companyIdx = companySort.indexOf(company);
      companySort.splice(companyIdx, 1);
      this.setData({
        companySort: companySort
      })
    }


    listInput.splice(index, 1);
    this.setData({
      listInput: listInput
    });
  },

  bindDateChange: function (e) {
    console.log(e);
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    var property = e.currentTarget.dataset.index;
    var objDate = this.data.objDate;
    objDate[property] = e.detail.value;
    this.setData({
      objDate: objDate
    })
    console.log(objDate);
  },
  editDateChange: function (e) {
    console.log(e);
    var property = e.currentTarget.dataset.day;
    var editDate = {};
    editDate[property] = e.detail.value;
    this.setData({
      editDate: editDate
    })

  },

  moreMsg: function () {
    this.setData({
      show: true
    })
  },
  hideMask: function () {
    this.setData({
      show: false
    })
  },
  choseItem: function (e) {
    var idx = e.currentTarget.dataset.index;
    var title = this.data.list[idx].title;
    var img = this.data.list[idx].img;
    var name = this.data.list[idx].name;
    var listInput = this.data.listInput;
    var obj = {};
    obj.title = title;
    obj.img = img;
    obj.name = name;

    /**** 计算添加条数 start ****/
    var key = name.toLowerCase().replace('_','');
    this.sumItemLength(true, key);
    /**** 计算添加条数 end ****/

    listInput.push(obj);
    this.setData({
      listInput: listInput,
      show: false
    })
  },

  addback: function () {
    var that = this;
    var imgList = this.data.imgList;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res);
        var tempFilePaths = res.tempFilePaths[0];
        imgList.push(tempFilePaths);
        console.log(imgList);
        that.setData({
          imgList: imgList,
          tempFilePaths: tempFilePaths
        })
      }
    })
  },
  editback: function () {
    var that = this;
    var imgList = this.data.imgList;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths[0];
        imgList.pop();
        imgList.push(tempFilePaths);
        that.setData({
          imgList: imgList,
          tempFilePaths: tempFilePaths
        })
      }
    })
  },
  avatarChose: function () {
    var headshot = this.data.headshot;
    headshot.flag = true;
    this.setData({
      headshot: headshot
    });
    this.hideMask();
  },
  uploadAvatar: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed', 'original'],
      sourceType: ['album', 'camera'],

      success: function (res) {
        var headshot = that.data.headshot;
        var tempFilePaths = res.tempFilePaths[0];
        headshot.img = tempFilePaths;
        that.setData({
          headshot: headshot
        })
      }
    })
  },
  //获取焦点时取值，从而获取在companySort里的下标
  focuseCompany: function (e) {
    var value = e.detail.value;
    var idx;
    var companySort = this.data.companySort;
    idx = companySort.indexOf(value);

    this.setData({
      idx: idx
    })

    oldCompany = e.detail.value;
  },

  listenCompany: function (e) {
    var value = e.detail.value;
    var idx = this.data.idx;
    var companySort = this.data.companySort;
    
    if (idx > -1 && value) {
      companySort[idx] = value;
    } else if (value && (companySort.indexOf(value) == -1)) {
      companySort.push(value);
    } else if(value === ''){
      companySort.splice(companySort.indexOf(oldCompany),1);
    }

    this.setData({
      companySort: companySort
    })

    /* 判断编辑值是否改变 */
    newCompany = e.detail.value;
    (oldCompany === newCompany && !dirty) ? dirty = false : dirty = true;

  },
  inputCompany: function (e) {
    var company = e.detail.value
    this.setData({
      currentCompany: company
    })
  },

  changeName: function (e) {
    var oldName = this.data.name;
    if(oldName != e.detail.value){
      dirty = true;
    }
    this.setData({
      name: e.detail.value
    })
  },
  skipToSort: function () {
    wx.navigateTo({
      url: "./sort-company/sort-company?company=" + this.data.companySort,
    })
  },

  /**************控制 来源选择 模态框 start********************/
  choseSource:function(){
    this.setData({
      showSource: true
    })
  },
  hideSources: function(){
    this.setData({
      showSource: false
    })
  },
  hasSource: function(e){
    var source = e.currentTarget.dataset.source;

    this.setData({
      source: source,
      showSource: false
    })
  },
  /**************控制 来源选择 模态框 end********************/

  /* 保存信息 */
  submit: function (e) {
    var that = this;
    var data = e.detail.value;
    var imgList = that.data.imgList; //图片列表
    var arr = [];
    var preKey;
    var headshot = that.data.headshot;
    var mInput = that.data.mInput ? that.data.mInput : '';
    /* 用来判断是否点击编辑进入 */
    var editId = this.data.editId;
    editId && (data.id = editId);

    for (var key in data) {
      var attr = /.+[^0-9]/.exec(key)[0];
      if (/.+[0-9]+/.test(key) && preKey == attr) {
        data[attr].push(data[key]);
      } else if (/.+[0-9]+/.test(key) && preKey != attr && data[attr] == undefined) {
        arr = [];
        arr.push(data[key]);
        data[attr] = arr;
      } else if (/.+[0-9]+/.test(key) && data[attr] != undefined) {
        data[attr].push(data[key]);
      }
      preKey = attr;
    }

    data.company = this.data.companySort;
    console.log(data);
    
    if(data.company == '') {
      wx.showModal({
        title: '提示',
        content: '请添加公司名',
        showCancel: false
      })
      return;
    }

    if (editId && dirty) { /********************编辑的时候验证名片信息是否存在*****************/
      app.Verification(function (token) {
        wx.request({
          url: constract.inpExist,
          header: { token: token },
          data: { company: data.company.join(','), name: data.name },
          success: (res) => {
            if (+res.data.code === 13000) {
              wx.showModal({
                title: '提示',
                content: '该名片信息已存在',
                showCancel: false
              })
            } else {
              saveAll(that,data,imgList,arr,preKey,headshot,mInput,editId);
            }
          }
        })
      })
    } else {
      saveAll(that,data,imgList,arr,preKey,headshot,mInput,editId);
    }

  }

})